<?php

namespace app\modules\api\controllers;

use app\models\Agent;
use app\models\ApiException;
use app\models\Card;
use app\models\CardDailyUsage;
use app\models\SubUser;
use app\models\User;

/**
 * 用量
 * Class UsageController
 * @package app\modules\api\controllers
 */
class UsageController extends BaseController
{
    /**
     * 依次尝试根据id ICCID MSISDN IMSI获取卡
     * @param Agent|User|SubUser $user 登录代理商或用户
     * @return Card
     * @throws ApiException
     */
    private function getCard($user = null)
    {
        $id = $this->json('id');
        $iccid = $this->json('iccid');
        $msisdn = $this->json('msisdn');
        $imsi = $this->json('imsi');

        $card = null;
        if (!empty($id)) {
            $card = Card::findOne(['id' => $id]);
        } elseif (!empty($iccid)) {
            $card = Card::findOne(['iccid' => $iccid]);
        } elseif (!empty($msisdn)) {
            $card = Card::findOne(['msisdn' => $msisdn]);
        } elseif (!empty($imsi)) {
            $card = Card::findOne(['imsi' => $imsi]);
        }

        if (!empty($card)) {
            if (!empty($user)) {
                if (($user instanceof Agent) && $card->agent_id != $user->id) {
                    throw new ApiException('NOT_FOUND', '没有找到卡信息。');
                }
                if (($user instanceof User) && $card->uid != $user->id) {
                    throw new ApiException('NOT_FOUND', '没有找到卡信息。');
                }
                if (($user instanceof SubUser) && $card->uid != $user->uid) {
                    throw new ApiException('NOT_FOUND', '没有找到卡信息。');
                }
            }
        }

        return $card;
    }

    /**
     * 日用量
     * 输入
     * {
     *     date,
     *     iccid,
     *     msisdn,
     *     imsi
     * }
     * 输出
     * {
     *     data,
     *     sms,
     *     voice
     * }
     * @throws ApiException
     */
    public function actionDaily()
    {
        $user = $this->loginUser();

        $this->checkJson([
            ['date', 'required'],
        ]);

        $card = $this->getCard($user);
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }

        $usage = CardDailyUsage::findOne(['date' => $this->json('date'), 'card_id' => $card->id]);
        if (empty($usage)) {
            throw new ApiException('NOT_FOUND', '没有找到用量信息。');
        }
        return $usage->getAttributes(['data', 'sms', 'voice']);
    }
}
